/**
 * Created by kule on 2017/10/30.
 */
import promiseDelay from './promiseDelay';
import isPromise from './isPromise';

export const TimeoutError = {
    message: 'timeout',
};
export const isTimeout = (res) => {
    return res === TimeoutError;
};
export const promiseTimeout = (promise, timeout = 1000, {
    isReject = true,
    result = TimeoutError,
} = {}) => {
    const _promise = isPromise(promise) ?
        promise :
        (new Promise(promise));
    const wait = promiseDelay(timeout)
        .then(() => {
            return Promise[isReject ? 'reject' : 'resolve'](result);
        });
    return Promise.race([_promise, wait]);
};

export const genPromiseWithTimeout=(runner,timeout=3000,defResult,isReject)=>{
    const task=new Promise(function(resolve,reject){
        runner(resolve,reject);
    });
    return promiseTimeout(task,timeout,{
        isReject,
        defResult
    });
};

export default promiseTimeout;